<?php

namespace app\qsapi\service;

use app\admin\model\game\BoxPcGameSource;
use app\qsapi\model\BoxAd;
use app\qsapi\model\BoxGame;
use app\qsapi\model\BoxGameCate;
use app\qsapi\model\BoxOpenAd;
use app\qsapi\model\BoxResourceBanner;
use app\qsapi\model\BoxResourcePosition;
use app\qsapi\model\BoxResourceTab;
use app\qsapi\model\game\BoxPcGameEngine;
use think\cache\driver\Redis;
use think\Db;

class BoxAdService extends BaseService
{

    private $scene = [
        'index' => 2,
        'my' => 5
    ];

    /**
     * Desc : 开屏广告列表
     * User : you name
     * Date : 2024-04-16 13:37
     * @param $params
     * @return array
     */
    public function getSpreadList($params): array
    {
        $redis = new Redis(getRedisConfig());
        $deviceModel = strtolower($params['deviceModel'] ?? ''); //设备型号, 这里用来区分IPAD和PAD开屏广告与手机端开屏广告的区分
        $deviceType = $this->getPlatform();
        if($deviceModel == 'pad' || $deviceModel == 'ipad'){
            if($deviceType == 'android'){
                $deviceType = 'pad';
            }elseif($deviceType == 'ios'){
                $deviceType = 'ipad';
            }
        }
        $result = json_decode($redis->get('box_ad_spread_list_'.$deviceType)) ?? [];
        if(!empty($result))  return api_message($result);

        $model = new BoxAd();
        $where[] = ['show_type', '=', 1];
        $where[] = ['status', '=', 1];
        $where[] = ['type', '=', 1];
        $where[] = ['mark', '=', 1];
        $where[] = ['start_time', '<=', time()];
        $where[] = ['end_time', '>=', time()];
        $list = $model->field('id,title,cover,description,description,url,type,end_time')->where($where)->where(function ($query) use($deviceType) {
            $query->where(Db::raw("FIND_IN_SET('1',device)"));
            if (isset($this->adDevice[$deviceType])) {
                $device = $this->adDevice[$deviceType];
                $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
            }
        })->order('sort desc')->select();
        if (!$list) return api_message();
        $list = $list->toArray();
        if(!empty($list)){
            $end_time = min(array_column($list,'end_time')) ?? 0;
            foreach ($list as &$item) {
                $item['cover'] = imageUrl($item['cover']);
            }
            $expire_time = ($end_time - time()) ?? 0;
            $redis->set('box_ad_spread_list_'.$deviceType,json_encode($list),$expire_time);
        }
        return api_message($list);
    }

    /**
     * Desc : getBannerList
     * User : Steven
     * Date : 2024-06-25 09:58
     * @return array
     */
    public function getBannerList(): array
    {
        $model = new BoxAd();
        $where[] = ['show_type', '=', 3];
        $where[] = ['status', '=', 1];
        $where[] = ['type', '=', 1];
        $where[] = ['mark', '=', 1];
        $where[] = ['start_time', '<=', time()];
        $where[] = ['end_time', '>=', time()];
        $plateScene = $this->getPlate() ?? 'all';
        $plateScene = $this->plateScene[$plateScene] ?? 1;
        $where[]    = ['scene', '=', $plateScene];
        $list = $model->field('id,title,cover,description,content,url,game_id,bg_start,bg_end,bg_start,bg_end,jump_type')->where($where)->where(function ($query) {
            $query->where(Db::raw("FIND_IN_SET('1',device)"));
            if (isset($this->adDevice[$this->getPlatform()])) {
                $device = $this->adDevice[$this->getPlatform()];
                $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
            }
        })->order('sort desc')->select();
        if (!$list) return [];
        $list = $list->toArray();

        $gameEngineList = BoxPcGameEngine::where(['mark'=>1,'status'=>1])->select();
        $gameSourceList = BoxPcGameSource::where(['mark'=>1])->select();
        $gameEngineList     = array_column($gameEngineList ? $gameEngineList->toArray() : [], null, 'engine_key');
        $gameSourceList     = array_column($gameSourceList ? $gameSourceList->toArray() : [], null, 'package_id');
        // 判断平台
        $platform = strtolower($this->platform) ?? '';

        foreach ($list as $k => &$item) {
            $list[$k]['cover'] = imageUrl($item['cover']);
            if(isset($item['game_id']) && !empty($item['game_id'])){
                //获取当前游戏的一些基本信息
                $boxGameModel = new BoxGame();
                if(isset($this->device[$platform])){
                    $boxGameModel = $boxGameModel->alias('g')->where(function ($query) use($platform) {
                        $query->where(Db::raw("FIND_IN_SET('0',g.on_platform)"));
                        if (isset($this->device[$platform])) {
                            $device = $this->device[$platform];
                            $query->whereOr(Db::raw("FIND_IN_SET('{$device}',g.on_platform)"));
                        }
                    });
                }else{
                    $boxGameModel = $boxGameModel->alias('g');
                }

                //PC端游戏更新添加版本控制
                // if($platform == 'pc'){
                //     $boxGameModel = $boxGameModel->leftJoin('cq_box_pc_game_source a', 'a.package_id = g.pc_package_id')
                //         ->field('a.version game_version,g.pc_game_project_name,g.pc_game_file_name,a.file_url pc_game_download_url');
                // }

                $result = $boxGameModel->field('g.id,g.game_name,g.icon,g.cate_id,g.game_banner,g.status,g.open_type,g.android_package_name,g.android_download_url,g.ios_download_url,g.android_bag,g.ios_bag,g.ios_app_store_id,g.ios_bag_type,g.is_hot,g.is_transfer,g.is_yun,g.yun_hang_up_bag,g.pc_engine_key,g.pc_package_id,g.pc_open_type')->where(['g.id'=>$item['game_id'],'g.status'=>1,'g.mark'=>1])->find();
                $cate_list     = BoxGameCate::where([['status', '=', 1],['mark', '=', 1]])->field('id,name,sort')->order('sort desc')->select();
                $cate_list     = array_column($cate_list ? $cate_list->toArray() : [], null, 'id');
                $labels = [];
                if (!empty($result['android_bag'])) {
                    $result['android_bag'] = explode("/", $result['android_bag']);
                }
                if(!empty($result)){
                    if($platform == 'pc'){
                        if($result['pc_open_type'] == 0){
                            $result['game_version']           = $gameEngineList[$result['pc_engine_key']]['version'] ?? '';
                            $result['pc_game_download_url']   = $gameEngineList[$result['pc_engine_key']]['engine_download_url'] ?? '';
                            $result['file_name']              = $gameEngineList[$result['pc_engine_key']]['file_name'] ?? '';
                            $result['file_size']              = $gameEngineList[$result['pc_engine_key']]['file_size'] ?? '';
                            $result['decompression_size']     = $gameEngineList[$result['pc_engine_key']]['decompression_size'] ?? '';
                        }elseif ($result['pc_open_type'] == 1){
                            $result['game_version']           = $gameSourceList[$result['pc_package_id']]['version'] ?? '';
                            $result['pc_game_download_url']   = $gameSourceList[$result['pc_package_id']]['file_url'] ?? '';
                            $result['file_name']              = $gameSourceList[$result['pc_package_id']]['file_name'] ?? '';
                            $result['file_size']              = $gameSourceList[$result['pc_package_id']]['file_size'] ?? '';
                            $result['decompression_size']     = $gameSourceList[$result['pc_package_id']]['decompression_size'] ?? '';
                        }
                    }
                }

                $item['game_info'] = $result;
                if (isset($result['cate_id']) && !empty($result['cate_id'])) {
                    $cate_ids = explode(",", $result['cate_id']);
                    foreach ($cate_ids as $i => $v) {
                        if (isset($cate_list[$v])) {
                            $labels[$i] = $cate_list[$v]['name'];
                        }
                    }
                }
                $item['game_info']['labels'] = $labels;
            }

        }
        return $list;
    }

    /**
     *获取弹窗广告
     * @param string $pop_scene
     * @return array
     */
    public function getPopouList(string $pop_scene = 'index'): array
    {
        $model      = new BoxAd();
        $where[]    = ['show_type', '=', 2];
        $where[]    = ['status', '=', 1];
        $where[]    = ['type', '=', 1];
        $where[]    = ['mark', '=', 1];
        $where[]    = ['start_time', '<=', time()];
        $where[]    = ['end_time', '>=', time()];
        $plateScene = $this->getPlate() ?? 'all';
        $plateScene = $this->plateScene[$plateScene] ?? 1;
        $where[]    = ['scene', '=', $plateScene];
        $pop_scene  = $this->scene[$pop_scene] ?? 1;
        $list       = $model->field('id,title,cover,description,url,pop_time,pop_num,pop_scene,scene')->where($where)->where(function ($query) use ($pop_scene) {
            $query->where('pop_scene', $pop_scene)->whereOr('pop_scene', 1);
        })->where(function ($query) {
            $query->where(Db::raw("FIND_IN_SET('1',device)"));
            if (isset($this->adDevice[$this->getPlatform()])) {
                $device = $this->adDevice[$this->getPlatform()];
                $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
            }
        })->order('sort desc')->select();
        if (!$list) return api_message();
        $list = $list->toArray();
        foreach ($list as $k => $item) {
            $list[$k]['cover'] = imageUrl($item['cover']);
        }

        return api_message($list);
    }


    public function getResource($params): array
    {
        $platform = $this->getPlatform();
        $platform = $this->adDevice[$platform];
        $redis = new Redis(getRedisConfig());
        $list = $redis->get('qsapi:resource:position'.$platform);
        $list = $list ? json_decode($list, true) : [];
        if(!$list){
            $model = new BoxResourcePosition();
            $where[] = ['status', '=', 1];
            $where[] = ['mark', '=', 1];
            if (!empty($params)){
                $where[] = ['version', '<=', intval(implode('',explode('.',$params)))];
            }
            $list = $model->field('id,title,icon,link,sort,version,background,notes')->where($where)->where(function ($query) {
                $query->where(Db::raw("FIND_IN_SET('1',device)"));
                if (isset($this->adDevice[$this->getPlatform()])) {
                    $device = $this->adDevice[$this->getPlatform()];
                    $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
                }
            })->order('sort desc')->select();
            $list = $list ? $list->toArray() : [];
            if (!$list) return $list;
            foreach ($list as $k => $item) {
                $list[$k]['icon'] = imageUrl($item['icon']);

            }
            $redis->set('qsapi:resource:position'.$platform, json_encode($list), 5);
        }
        return $list;
    }

    /**
     * Desc : tab栏配置
     * User : you name
     * Date : 2024-01-13 14:14
     * @return array|null
     */
    public function getTab($params)
    {
        $redis = new Redis(getRedisConfig());
        $list = $redis->get('qsapi:resource:tab');
        $list = $list ? json_decode($list, true) : [];
        if(!$list){
            $model = new BoxResourceTab();
            $where[] = ['status', '=', 1];
            $where[] = ['mark', '=', 1];
            if (!empty($params)){
                $where[] = ['version', '<=', intval(implode('',explode('.',$params)))];
            }
            $list = $model->field('id,title,icon,bg_icon,link,sort,version')->where($where)->order('sort desc')->select();
            $list = $list ? $list->toArray() : [];
            if (!$list) return $list;
            foreach ($list as $k => $item) {
                $list[$k]['icon'] = imageUrl($item['icon']);

            }
            $redis->set('qsapi:resource:tab', json_encode($list), 5);
        }

        return api_message($list,'tab栏获取成功!');
    }


    /**
     * @return array
     */
    public function getNewResource()
    {
        $model = new BoxResourcePosition();
        $where[] = ['status', '=', 1];
        $where[] = ['mark', '=', 1];
        $list = $model->field('id,title,icon,link,sort,compoent')->where($where)->order('sort desc')->select();
        $list = $list ? $list->toArray() : [];
        if (!$list) return api_message($list);
        //获取对应的banner
        $ids = array_column($list, 'id');
        $where[] = ['b.show_type', '=', 3];
        $where[] = ['b.status', '=', 1];
        $where[] = ['b.type', '=', 1];
        $where[] = ['b.mark', '=', 1];
        $where[] = ['b.start_time', '<=', time()];
        $where[] = ['b.end_time', '>=', time()];
        $banner = (new BoxResourceBanner())->field('a.resource_id,b.id,b.title,b.cover,b.url')->where($where)->whereIn('resource_id', $ids)->alias('a')
            ->where(function ($query) {
                $query->where(Db::raw("FIND_IN_SET('1',device)"));
                if (isset($this->device[$this->getPlatform()])) {
                    $device = $this->device[$this->getPlatform()];
                    $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
                }
            })
            ->leftJoin('box_ad b', 'a.banner_id=b.id')->select();
        $banner = $banner ? $banner->toArray() : [];
        $banner_list = [];
        if ($banner) {
            foreach ($banner as $v) {
                $banner_list[$v['resource_id']][] = $v;
            }
        }
        foreach ($list as $k => $item) {
            $list[$k]['icon'] = imageUrl($item['icon']);
            $list[$k]['banner'] = isset($banner_list[$item['id']]) ? $banner_list[$item['id']] : [];
        }
        return api_message($list);
    }


    public function openGameAd()
    {
        $param = request()->param();
        $model = new BoxOpenAd();
        $list = $model->where('mark', 1)->where('status', 1);
        $where[] = ['start_time', '<=', time()];
        $where[] = ['end_time', '>=', time()];
        if (isset($param['time']) && !empty($param['time'])) {  //开服时间,查找当前开服中所有的游戏ID
            $list = $list->where('open_time', '=', $param['time']);
        }
        $list = $list->field('id,title,cover,description,description,url')->where($where)->where(function ($query) {
            $query->where(Db::raw("FIND_IN_SET('1',device)"));
            if (isset($this->adDevice[$this->getPlatform()])) {
                $device = $this->adDevice[$this->getPlatform()];
                $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
            }
        })->order('sort desc')->select();
        if (!$list) return api_message();
        $list = $list->toArray();
        foreach ($list as $k => $item) {
            $list[$k]['cover'] = imageUrl($item['cover']);
        }
        return api_message($list);
    }

}
